package com.lite.haru.alarmpolice.activity;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;

import com.lite.haru.R;
import com.lite.haru.constant.Constant;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

public class PoliceLoginAty extends KJActivity {

	@BindView(id = R.id.account)
	private EditText inputUsername;
	@BindView(id = R.id.pwd)
	private EditText inputPassword;
	@BindView(id = R.id.login, click = true)
	private TextView login;

	private SharedPreferences sp;
	private ProgressDialog mDialog;
	private String responseMsg = "";
	private String username;
	private String password;
	private static final int REQUEST_TIMEOUT = 5 * 1000;// 设置请求超时10秒钟
	private static final int SO_TIMEOUT = 10 * 1000; // 设置等待数据超时时间10秒钟
	private static final int LOGIN_OK = 1;

	@Override
	public void setRootView() {
		setContentView(R.layout.aty_alarm_login);
	}

	@Override
	public void initData() {
		judgeFirst();
		super.initData();
	}

	public void judgeFirst() {
		sp = getSharedPreferences("AlarmPoliceinfo", Activity.MODE_PRIVATE);
		String isFirst = sp.getString("isFirst", "");
		if ("".equals(isFirst)) {// 判断是否是第一次打开
		} else {
			startActivity(new Intent(this, AlarmMainAty.class));
			this.finish();
		}

	}

	@Override
	public void initWidget() {
		// 透明状态栏
		getWindow()
				.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		// // 透明导航栏
		// getWindow().addFlags(
		// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		super.initWidget();

	}

	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);

		switch (v.getId()) {
		case R.id.login:
			mDialog = new ProgressDialog(PoliceLoginAty.this);
			mDialog.setTitle("登陆");
			mDialog.setMessage("正在登陆服务器，请稍后...");
			mDialog.show();
			Thread loginThread = new Thread(new LoginThread());
			loginThread.start();
			break;

		default:
			break;
		}

	}

	private boolean loginServer(String username, String password) {
		boolean loginValidate = false;
		// 使用apache HTTP客户端实现
		String urlStr = Constant.url + "/LoginClientAction";
		HttpPost request = new HttpPost(urlStr);
		// 如果传递参数多的话，可以对传递的参数进行封装
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 添加用户名和密码
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", password));
		try {
			// 设置请求参数项
			request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpClient client = getHttpClient();
			// 执行请求返回相应
			HttpResponse response = client.execute(request);

			// 判断是否请求成功
			if (response.getStatusLine().getStatusCode() == 200) {
				loginValidate = true;
				// 获得响应信息
				responseMsg = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return loginValidate;
	}

	// 初始化HttpClient，并设置超时
	public HttpClient getHttpClient() {
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
		HttpClient client = new DefaultHttpClient(httpParams);
		return client;
	}

	// 检查网络状态
	public void CheckNetworkState() {
		boolean flag = false;
		ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		// 如果3G、wifi、2G等网络状态是连接的，则退出，否则显示提示信息进入网络设置界面
		if (mobile == State.CONNECTED || mobile == State.CONNECTING)
			return;
		if (wifi == State.CONNECTED || wifi == State.CONNECTING)
			return;
		showTips();
	}

	private void showTips() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle("没有可用网络");
		builder.setMessage("当前网络不可用，是否设置网络？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 如果没有网络连接，则进入网络设置界面
				startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				PoliceLoginAty.this.finish();
			}
		});
		builder.create();
		builder.show();
	}

	// Handler
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				mDialog.cancel();
				SharedPreferences.Editor editor = sp.edit();
				editor.putString("isFirst", "false");
				editor.putString("username", username);
				editor.putString("password", md5(password));
				editor.commit();
				Intent intent = new Intent();
				intent.setClass(PoliceLoginAty.this, AlarmMainAty.class);
				startActivity(intent);
				finish();
				break;
			case 1:
				mDialog.cancel();
				ViewInject.toast("账号或密码错误");
				break;
			case 2:
				mDialog.cancel();
				ViewInject.toast("URL验证失败");
				break;

			}

		}
	};

	// LoginThread线程类
	class LoginThread implements Runnable {

		@Override
		public void run() {
			username = inputUsername.getText().toString();
			password = inputPassword.getText().toString();

			// URL合法，但是这一步并不验证密码是否正确
			boolean loginValidate = loginServer(username, password);
			Message msg = handler.obtainMessage();
			if (loginValidate) {
				if (responseMsg.equals("success")) {
					msg.what = 0;
					handler.sendMessage(msg);
				} else {
					msg.what = 1;
					handler.sendMessage(msg);
				}

			} else {
				msg.what = 2;
				handler.sendMessage(msg);
			}
		}
	}

	/**
	 * MD5单向加密，32位，用于加密密码，因为明文密码在信道中传输不安全，明文保存在本地也不安全
	 * 
	 * @param str
	 * @return
	 */

	public static String md5(String str) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		char[] charArray = str.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++) {
			byteArray[i] = (byte) charArray[i];
		}
		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}
}
